package com.example.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class Demo1 {
    /**
     * 获取 html 页面
     *
     * http://127.0.0.1:8105/handle?url=https://mp.weixin.qq.com/s/XspiwxL9eEGmpPZxxBelbA
     * @param url
     * @return
     */
    @GetMapping("/handle")
    public Map<String, Object> handle(@RequestParam String url) {
        //设置必要参数
        DesiredCapabilities dcaps = new DesiredCapabilities();
        //ssl证书支持
        dcaps.setCapability("acceptSslCerts", true);
        //截屏支持
        dcaps.setCapability("takesScreenshot", true);
        //css搜索支持
        dcaps.setCapability("cssSelectorsEnabled", true);
        //js支持
        dcaps.setJavascriptEnabled(true);
        //驱动支持（第二参数表明的是你的phantomjs引擎所在的路径）
        dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "/usr/bin/phantomjs");
        //创建无界面浏览器对象
        PhantomJSDriver driver = new PhantomJSDriver(dcaps);

        //设置隐性等待（作用于全局）
        driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
        //打开页面
        driver.get(url);
        //查找元素
//        WebElement element = driver.findElement(By.id("img_valiCode"));

//        System.out.println(element.getAttribute("src"));

//        WebElement video = driver.findElementByTagName("video");
//        String src = video.getAttribute("src");
        String pageSource = driver.getPageSource();

        Map<String, Object> map = new HashMap<>();
//        map.put("result", video.getText());
//        map.put("src", src);
        map.put("pageSource", pageSource);

        // 关闭
        driver.close();
        return map;
    }

    @GetMapping("/page")
    public Map<String, Object> page(@RequestParam String url) throws InterruptedException {
        //设置必要参数
        DesiredCapabilities dcaps = new DesiredCapabilities();
        //ssl证书支持
        dcaps.setCapability("acceptSslCerts", true);
        //截屏支持
        dcaps.setCapability("takesScreenshot", true);
        //css搜索支持
        dcaps.setCapability("cssSelectorsEnabled", true);
        //js支持
        dcaps.setJavascriptEnabled(true);
        //驱动支持（第二参数表明的是你的phantomjs引擎所在的路径）
        dcaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "/usr/bin/phantomjs");
        //创建无界面浏览器对象
        PhantomJSDriver driver = new PhantomJSDriver(dcaps);

        /*Dimension targetSize= new Dimension(300,500); //设置窗口大小为1024*768
        driver.manage().window().setSize(targetSize);
        //Thread.sleep(5000);

        Point targetPosition01= new Point(300, 600); //设置窗口左上角那个点出现的位置为(300,600)

        driver.manage().window().setPosition(targetPosition01);
        //Thread.sleep(5000);

        driver.manage().window().maximize();
        Thread.sleep(5000);*/

        //设置隐性等待（作用于全局）
        driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
        //打开页面
        driver.get(url);
        //查找元素
//        WebElement element = driver.findElement(By.id("img_valiCode"));

//        System.out.println(element.getAttribute("src"));

        WebElement html = driver.findElementByTagName("html");
        String text = html.getText();
        String tagName = html.getTagName();

        String title = html.findElement(By.cssSelector("meta[property=\"og:title\"]")).getAttribute("content");
        String desc = html.findElement(By.cssSelector("meta[property=\"og:description\"]")).getAttribute("content");
        String image = html.findElement(By.cssSelector("meta[property=\"og:image\"]")).getAttribute("content");

//        WebElement richMediaContent = html.findElement(By.className("rich_media_content"));

        List<String> videoLinks = new ArrayList<>();
        Map<Integer, String> map = new HashMap<>();

        List<WebElement> videoList = html.findElements(By.tagName("video"));
        log.info("[video-size] = " + videoList.size());

        if (!CollectionUtils.isEmpty(videoList) && videoList.size() > 0) {
            for (WebElement element : videoList) {
                String link = element.getAttribute("src");
                log.info("[src] = " + link);
//                int key = element.getLocation().getY();// 视频元素的 top 位置
//                log.info("[top-location] = " + key);
//                log.info("{Rectangle} : X = " + element.getRect().getX() + " Y = " + element.getRect().getY());
                videoLinks.add(link);
//                map.put(key, link);
            }
        }

        List<WebElement> iframeList = html.findElements(By.tagName("iframe"));
        log.info("[iframe-size] = " + iframeList.size());

        if (!CollectionUtils.isEmpty(iframeList) && iframeList.size() > 0) {
            for (WebElement iframe : iframeList) {
                String link = iframe.getAttribute("src");
//                int key = iframe.getLocation().getY();// 视频元素的 top 位置
//                log.info("[top-location] = " + key);
//                log.info("{Rectangle} : X = " + iframe.getRect().getX() + " Y = " + iframe.getRect().getY());
                videoLinks.add(link);
//                map.put(key, link);
            }
        }

        /*Integer[] keys = map.keySet().toArray(new Integer[map.size()]);
        log.info("[keys] = " + Arrays.toString(keys));

        Arrays.sort(keys);// 按 top 位置排序
        log.info("[keys] = " + Arrays.toString(keys));
        Arrays.stream(keys).forEach(info -> videoLinks.add(map.get(info)));*/


        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("text", text);
        resultMap.put("tagName", tagName);
        resultMap.put("title", title);
        resultMap.put("desc", desc);
        resultMap.put("image", image);
        resultMap.put("videoLinks", videoLinks);

        // 关闭
//        driver.close();
        driver.quit();
        return resultMap;
    }

    @GetMapping("/test")
    public Map<String, Object> test() {
        Map<String, Object> map = new HashMap<>();
        map.put("t1", "123");
        return map;
    }
}
